package org.wangchaocheng.cloudgallery.i18n;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.LocaleResolver;

/**
 * 国际化配置
 *
 * @author wangchaocheng
 * @date 2025/04/23
 */
@Component
@RequiredArgsConstructor
public class I18nConfig implements LocaleResolver {

    @Getter
    @Value("${spring.messages.basename}")
    private String messageBasename;

    @Getter
    @Value("${spring.messages.encoding}")
    private String messageEncoding;

    private final HttpServletRequest request;

    public Locale resolveLocale() {
        return resolveLocale(request);
    }

    /**
     * 从HttpServletRequest中获取Locale
     *
     * @param request httpServletRequest
     * @return {@link Locale}
     */
    @NotNull
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        // 从请求参数中获取语言参数（第一优先级）
        String language = request.getParameter("lang");
        if (StringUtils.isBlank(language)) {
            // 若请求参数中未获取到，则从请求头中获取（第二优先级）
            language = request.getHeader("X-Language");
        }
        // 若获取到语言，则构建语言环境
        if (StringUtils.isNotEmpty(language)) {
            // zh_CN
            String[] s = language.split("-");
            // 国家，地区
            return new Locale(s[0], s[1]);
        }
        // 默认使用主机的语言环境
        return Locale.getDefault();
    }

    /**
     * 用于实现Locale的切换。比如SessionLocaleResolver获取Locale的方式是从session中读取，但如果
     * 用户想要切换其展示的样式(由英文切换为中文)，那么这里的setLocale()方法就提供了这样一种可能
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @param locale   locale
     */
    @Override
    public void setLocale(@NotNull HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}
